<template>
    <div class="chat-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>融云即时通讯</span>
          <el-button
            v-if="!isConnected"
            style="float: right; padding: 3px 0"
            type="text"
            @click="connect"
          >
            连接
          </el-button>
          <el-button
            v-else
            style="float: right; padding: 3px 0"
            type="text"
            @click="disconnect"
          >
            断开
          </el-button>
        </div>
        
        <div class="chat-main">
          <div class="conversation-list">
            <el-menu
              :default-active="activeConversation"
              @select="handleSelectConversation"
            >
              <el-menu-item
                v-for="conversation in conversationList"
                :key="`${conversation.conversationType}-${conversation.targetId}`"
                :index="`${conversation.conversationType}-${conversation.targetId}`"
              >
                <span>{{ getConversationTitle(conversation) }}</span>
              </el-menu-item>
            </el-menu>
          </div>
          
          <div class="message-area">
            <div class="message-list" ref="messageList">
              <div
                v-for="(message, index) in messages"
                :key="index"
                class="message-item"
                :class="{ 'self-message': message.messageDirection === 1 }"
              >
                <div class="message-content">
                  {{ message.content.content }}
                </div>
                <div class="message-time">
                  {{ formatTime(message.sentTime) }}
                </div>
              </div>
            </div>
            
            <div class="message-input">
              <el-input
                v-model="inputMessage"
                placeholder="请输入消息"
                @keyup.enter.native="sendMessage"
              ></el-input>
              <el-button
                type="primary"
                @click="sendMessage"
                :disabled="!isConnected"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script>
  import {
    initRongCloud,
    connectRongCloud,
    disconnectRongCloud,
    getConversationList,
    sendTextMessage,
    getHistoryMessages,
    addRongCloudListener,
    removeRongCloudListener,
    RongCloudEvents,
    RongCloudConversationType
  } from '@/utils/rongcloud'
  

  import { getToken } from '@/api/cs';
  export default {
    name: 'Chat',
    data() {
      return {
        appKey: 'cpj2xarlciqbn', // 替换为你的AppKey
        
        token: '', // 替换为你的Token

        isConnected: false,
        conversationList: [],
        messages: [],
        activeConversation: null,
        currentTargetId: 50527698, //目标id
        currentConversationType: RongCloudConversationType.PRIVATE,
        inputMessage: '',
        userId: '1', // 当前用户ID
        isCS:'',
        isSend:'',
      }
    },
    mounted() {
      this.init()
      this.getToken0()
    },
    beforeDestroy() {
      this.removeListeners()
      if (this.isConnected) {
        this.disconnect()
      }
    },
    methods: {
      // 从后端获取融云token
      getToken0(){
        getToken().then((res)=>{
          this.token=res.data.token
          this.isCS=res.data.isCS,
          this.isSend=res.data.isSend,
          console.log(res.data.token)

        })
      
      },
      async init() {
        try {
          // 初始化融云
          await initRongCloud(this.appKey)
          
          // 添加事件监听
          this.addListeners()
          
          this.$message.success('融云初始化成功')
        } catch (error) {
          this.$message.error('融云初始化失败: ' + error)
        }
      },
      
      addListeners() {
        // 连接状态监听
        addRongCloudListener(RongCloudEvents.CONNECTING, () => {
          this.$message.info('正在连接服务器...')
        })
        
        addRongCloudListener(RongCloudEvents.CONNECTED, () => {
          this.isConnected = true
          this.$message.success('已连接到服务器')
          this.loadConversationList()

          })
        
        addRongCloudListener(RongCloudEvents.DISCONNECT, () => {
          this.isConnected = false
          this.$message.warning('已断开连接')
        })
        
        // 消息监听
        addRongCloudListener(RongCloudEvents.MESSAGES, (event) => {
          const newMessages = event.messages
          newMessages.forEach(message => {
            // 只显示当前会话的消息
            if (
              message.targetId === this.currentTargetId &&
              message.conversationType === this.currentConversationType
            ) {
              this.messages.push(message)
              this.scrollToBottom()
            }
          })
        })
      },
      
      removeListeners() {
        removeRongCloudListener(RongCloudEvents.CONNECTING)
        removeRongCloudListener(RongCloudEvents.CONNECTED)
        removeRongCloudListener(RongCloudEvents.DISCONNECT)
        removeRongCloudListener(RongCloudEvents.MESSAGES)
      },
      
      async connect() {
        try {
          const result = await connectRongCloud(this.token)
          if (result.code === 0) {
            this.userId = result.data.userId
            this.$message.success(`连接成功, 用户ID: ${this.userId}`)
 // 如果不是客服且需要发送问候
 if(this.isCS != 1 && this.isSend != 0) {
        // 设置明确的延迟参数
        const delayTime = 1000; // 1000毫秒=1秒
        const targetUserId = "50527698"; // 明确的客服ID
        const conversationType = RongCloudConversationType.PRIVATE; // 明确的私聊类型
        const greetingMessage = "售后客服您好，我有问题想请教"; // 明确的问候语
        
        setTimeout(() => {
          sendTextMessage(
            targetUserId,          // 接收者ID
            conversationType,     // 会话类型
            greetingMessage       // 消息内容
          ).then(result => {
            if (result.code === 200) { // 注意检查融云实际返回的成功码
              console.log(`延迟${delayTime}ms后，自动问候发送成功`);
              this.loadConversationList();
            }
          }).catch(error => {
            console.error('延迟发送失败:', error);
          });
        }, delayTime); // 使用定义的延迟时间
        
        console.log(`已设置${delayTime}ms延迟发送`);
      }
    }
        } catch (error) {
          this.$message.error('连接失败: ' + error)
        }
      },
      
      async disconnect() {
        try {
          await disconnectRongCloud()
          this.$message.success('已断开连接')
        } catch (error) {
          this.$message.error('断开连接失败: ' + error)
        }
      },
      
      async loadConversationList() {
        try {
          const result = await getConversationList()
          if (result.code === 0) {
            this.conversationList = result.data
            if (this.conversationList.length > 0) {
              // 默认选择第一个会话
              const firstConversation = this.conversationList[0]
              this.handleSelectConversation(
                `${firstConversation.conversationType}-${firstConversation.targetId}`
              )
            }
          } else {
            this.$message.error('获取会话列表失败: ' + result.code)
          }
        } catch (error) {
          this.$message.error('获取会话列表失败: ' + error)
        }
      },
      
      handleSelectConversation(index) {
        const [conversationType, targetId] = index.split('-')
        this.currentConversationType = parseInt(conversationType)
        this.currentTargetId = targetId
        this.activeConversation = index
        this.loadHistoryMessages()
      },
      
      async loadHistoryMessages() {
        if (!this.currentTargetId || !this.currentConversationType) return
        
        try {
          const result = await getHistoryMessages(
            this.currentTargetId,
            this.currentConversationType,
            {
              count: 20
            }
          )
          
          if (result.code === 0) {
            this.messages = result.data.list.reverse()
            this.scrollToBottom()
          } else {
            this.$message.error('获取历史消息失败: ' + result.code)
          }
        } catch (error) {
          this.$message.error('获取历史消息失败: ' + error)
        }
      },
      
      async sendMessage() {
        if (!this.inputMessage.trim()) {
          this.$message.warning('消息内容不能为空')
          return
        }
        
        if (!this.isConnected) {
          this.$message.warning('请先连接到融云服务器')
          return
        }
        
        if (!this.currentTargetId || !this.currentConversationType) {
          this.$message.warning('请先选择会话')
          return
        }
        
  try {
    // 创建临时消息
    const tempMessage = {
      messageId: `temp_${Date.now()}`,
      content: { content: this.inputMessage },
      sentTime: Date.now(),
      messageDirection: 1,
      targetId: this.currentTargetId,
      conversationType: this.currentConversationType,
      sendStatus: 'sending'
    };
    
    // 更新UI
    this.messages.push(tempMessage);
    this.scrollToBottom();
    this.inputMessage = '';
    
    // 发送到服务器
    const result = await sendTextMessage(

      this.currentTargetId,
      this.currentConversationType,
      tempMessage.content.content
    );
    
    // 处理结果
    if (result.code === 0) {
      const index = this.messages.findIndex(m => m.messageId === tempMessage.messageId);
      if (index !== -1) {
        this.$set(this.messages, index, {
          ...result.data,
          sendStatus: 'success'
        });
      }
    } else {
      this.handleSendFailed(tempMessage.messageId);
    }
  } catch (error) {
    this.handleSendFailed(tempMessage.messageId);
  }
},

handleSendFailed(tempId) {
  const index = this.messages.findIndex(m => m.messageId === tempId);
  if (index !== -1) {
    this.$set(this.messages[index], 'sendStatus', 'failed');
  }
  this.$message.error('消息发送失败');
},
handleSendFailed(tempId) {
  const index = this.messages.findIndex(m => m.messageId === tempId);
  if (index !== -1) {
    this.$set(this.messages[index], 'sendStatus', 'failed');
  }
  this.$message.error('消息发送失败');
},
      
      getConversationTitle(conversation) {
        switch (conversation.conversationType) {
          case RongCloudConversationType.PRIVATE:
            return `私聊: ${conversation.targetId}`
          case RongCloudConversationType.GROUP:
            return `群聊: ${conversation.targetId}`
          case RongCloudConversationType.CHATROOM:
            return `聊天室: ${conversation.targetId}`
          default:
            return `未知会话: ${conversation.targetId}`
        }
      },
      
      formatTime(timestamp) {
        return new Date(timestamp).toLocaleTimeString()
      },
      
      scrollToBottom() {
        this.$nextTick(() => {
          const container = this.$refs.messageList
          if (container) {
            container.scrollTop = container.scrollHeight
          }
        })
      }
    }
  }
  </script>
  
  <style scoped>
  .chat-container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .chat-main {
    display: flex;
    height: 500px;
  }
  
  .conversation-list {
    width: 200px;
    border-right: 1px solid #ebeef5;
    overflow-y: auto;
  }
  
  .message-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 10px;
  }
  
  .message-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
  }
  
  .message-item {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 5px;
    background-color: #f5f7fa;
    max-width: 70%;
  }
  
  .self-message {
    margin-left: auto;
    background-color: #409eff;
    color: white;
  }
  
  .message-content {
    word-wrap: break-word;
  }
  
  .message-time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    text-align: right;
  }
  
  .message-input {
    display: flex;
    margin-top: 10px;
  }
  
  .message-input .el-input {
    flex: 1;
    margin-right: 10px;
  }
  </style>